#!/usr/bin/python
import json
import csv
import datetime
import requests
import sys



# 节目对象
class Program(object):
    def __init__(self):
        # 中文名称
        self.name = ''
        # 唯一编目
        self.code = ''


# 通过URL获取json串
def get_url_json(type):
    url = ""
    if type == "4K":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/local?code=4K&languageType=0&categoryCode=&pageNo=1&pageSize=2000&status=1"
    elif type == "电视剧":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/series?code=series&field=undefined&categoryCode=&pageNo=1&pageSize=5000&status=1"
    elif type == "电影":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/program?code=movie&field=undefined&categoryCode=&pageNo=1&pageSize=8000&status=1"
    elif type == "纪实":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/series?code=documentary&field=undefined&categoryCode=&pageNo=1&pageSize=200&status=1"
    elif type == "少儿":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/local?code=children&languageType=0&categoryCode=&pageNo=1&pageSize=1000&status=1"
    elif type == "综艺":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/series?code=variety&field=undefined&categoryCode=&pageNo=1&pageSize=500&status=1"
    # print(url)
    r = requests.get(url)
    json_str = r.json()
    return json_str

# 根据code获取详情页数据
def get_url_json2(code,type):
    url = ""
    if type == "4K":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/local?code=4K&languageType=0&categoryCode=&pageNo=1&pageSize=2000&status=1"
    elif type == "电视剧":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/item/series?code="+code+"&categoryCode=series"
    elif type == "电影":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/item/program?code="+code
    elif type == "纪实":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/series?code=documentary&field=undefined&categoryCode=&pageNo=1&pageSize=200&status=1"
    elif type == "少儿":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/local?code=children&languageType=0&categoryCode=&pageNo=1&pageSize=1000&status=1"
    elif type == "综艺":
        url = "http://api.hd2.xjitv.cn:9090/itv-api/series?code=variety&field=undefined&categoryCode=&pageNo=1&pageSize=500&status=1"
    r = requests.get(url)
    json_str = r.json()
    return json_str

# 根据code获取详情页数据
def get_url_json_series(code):
    url = "http://api.hd2.xjitv.cn:9090/itv-api/item/series?code="+code+"&categoryCode=series"
    r = requests.get(url)
    json_str = r.json()
    return json_str


# 读文件内容
def read_file2(filepath):
    with open(filepath, 'rb') as f:
        line = f.read()
    line = line.strip().decode('utf-8')
    return line


# 解析json文件
def resolve_json_file(path):
    file = open(path, "rb")
    fileJson = json.load(file)
    resources = fileJson["resources"]
    return resources


# 解析json数据
def resolve_json_data(data):
    json_str = json.dumps(data)
    json_object = json.loads(json_str)
    resources = json_object["resources"]
    return resources


# 解析json中的json数组
def reslove_array_json(data):
    list_json = json.loads(json.loads(data))
    if len(list_json) > 1:
        runeval = list_json[0]["RunEval"]
    for item in list_json[1:]:
        name = item["name"]
        print(name)


# 写入csv文件
def write_csv(f,name,code,description):
    # 1. 创建文件对象
    # f = open(path,'w',encoding='utf-8')
    # 2. 基于文件对象构建 csv写入对象
    csv_writer = csv.writer(f)
    # 3. 构建列表头
    # csv_writer.writerow(["名称","code"])
    # 4. 写入csv文件内容
    csv_writer.writerow([name,code,description])
    # 5. 关闭文件
    # f.close()

# 将json内容写入CSV文件，带表头
def write_file_csv(resources,type):
    csvPath = "/home/csv/新疆电信"+program_type+datetime.datetime.now().strftime('%Y-%m-%d') +".csv"
    # 1.创建文件对象
    f = open(csvPath,'w',encoding='utf-8-sig')
    # 2.基于文件对象构建 csv写入对象
    csv_writer = csv.writer(f)
    # 3. 构建列表头
    csv_writer.writerow(["名称","code","description"])
    # 4. 写入csv文件内容
    # 循环数组
    for data in resources:
        # 将字典转换为字符串
        json_str = json.dumps(data)
        # 将字符串转换为字典
        json_object = json.loads(json_str)
        # print(json_object["name"] ,":" , json_object["code"])
        josn_detail = get_url_json2(json_object["code"], type)

        if type == "电影":
            write_csv(f ,josn_detail["name"] , josn_detail["code"] , josn_detail["description"])
        elif type == "电视剧":
            series = josn_detail["series"]
            write_csv(f ,series["name"] , series["code"] , series["description"])


    # 5. 关闭文件
    f.close()



# 运行
if __name__ == '__main__':
    # filePath = "C:/data/git/doc_hubert/doc/05项目/机顶盒抓包/json.json"
    # csvPath = "C:/data/git/doc_hubert/doc/05项目/机顶盒抓包/数据"+datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') +".csv"

    #sys.argv[0] 类似于shell中的$0,但不是脚本名称，而是脚本的路径
    #sys.argv[1] 表示传入的第一个参数，既 hello
    print(len(sys.argv) , sys.argv[1])

    if len(sys.argv) < 2:
        print("请输出传参，样例为：python demo.py argv1(url) argv2(type)")
        # 终止运行
        sys.exit()
    # 类型
    program_type = sys.argv[1]
    # 通过URL获取json数据
    jsonData = get_url_json(program_type)
    # 获取json中某个属性值，这里是一个json数组
    resources = resolve_json_data(jsonData)

    # 写入内容
    write_file_csv(resources,program_type)


